import os
import random
import time
import exifread
from datetime import datetime
from pathlib import Path
import re


filedir="E:\\CRdata"

def get_new_file_name(file):
    # 获取exif属性
    with open(file, 'rb') as f:
        img_exif = exifread.process_file(f)
    shot_time = img_exif.get('EXIF DateTimeOriginal')
    if shot_time:
        shot_time = datetime.strptime(str(shot_time), "%Y:%m:%d %H:%M:%S").strftime("%Y%m%d_%H%M%S")
        print("shot_time:",shot_time)
    else:
        mtime = os.path.getmtime(file)
        shot_time = time.strftime("%Y%m%d_%H%M%S", time.localtime(mtime))
        print("mtime:",shot_time)
    new_file_name = shot_time + "_S" + str(random.randint(1, 9)) + str(random.randint(100000, 999999))
    shotname, extension = os.path.splitext(file)
    return new_file_name + extension


def rename(file):
    new_file_name = get_new_file_name(file)
    new_file = os.path.join(os.path.dirname(file), new_file_name)
    os.rename(file, new_file)
    print("renamed file:",file,"to:",new_file)

def main():
    dir = os.walk(filedir)
    for i in dir:
        for file_name in i[2]:
            searchObj = re.search(r'(20[1-2]\d{5}).*', file_name)  # 过滤掉本身命名中已经带日期的图片
            if searchObj:
                continue
            searchObj = re.search(r'(20[1-2]\d[-,_]\d{2}[-,_]\d{2}).*', file_name)# 过滤掉本身命名中已经带日期的图片
            if searchObj:
                continue
            suffix = Path(file_name).suffix
            if suffix in ['.jpg','.JPG','.PNG','.png','.mp4','.MOV']:
                file = os.path.join(i[0], file_name)
                rename(file)
            else:
                print(suffix)

if __name__ == '__main__':
    main()

